package com.feinno.urcs.group.servlet.handler;

import com.feinno.threading.Future;
import com.feinno.urcs.group.GroupConfiguration;
import com.feinno.urcs.group.api.GroupOfflineMessageService;
import com.feinno.urcs.group.api.GroupService;
import com.feinno.urcs.group.api.GroupTerminalService;
import com.feinno.urcs.group.entity.GroupIndex;
import com.feinno.urcs.group.entity.GroupInfo;
import com.feinno.urcs.group.entity.GroupOfflineMessageIndex;
import com.feinno.urcs.group.siptask.task.GroupInviteArgs;
import com.feinno.urcs.group.siptask.task.GroupMessageArgs;
import com.feinno.urcs.offline.MessageResult;
import com.feinno.urcs.offline.SendMessageHandler;
import com.feinno.urcs.storage.entity.MessageBase;
import com.feinno.urcs.types.MobileNo;
import org.helium.framework.annotations.ServiceImplementation;
import org.helium.framework.annotations.ServiceSetter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sip.address.URI;

/**
 * @author Li.Hongbo <lihongbo@feinno.com>
 */
@ServiceImplementation(id = "group:GroupSendTextMessageHandler")
public class GroupSendTextMessageHandler implements SendMessageHandler {

	private static final Logger LOGGER = LoggerFactory.getLogger(GroupSendTextMessageHandler.class);

	@ServiceSetter
	private GroupOfflineMessageService offlineMessageService;
	@ServiceSetter
	private GroupTerminalService terminalService;
	@ServiceSetter
	private GroupService groupService;


	@Override
	public Future<MessageResult> send(MessageBase message) {
		Future<MessageResult> future = new Future<>();
		String messageId = message.getMessageId();
		try {
			LOGGER.info("GroupSendTextMessageHandler send start message="+message.toJsonObject().toString());
			GroupOfflineMessageIndex messageIndex = offlineMessageService.getOfflineMessageIndexByMessageBaseId(messageId);
			if (null == messageIndex) {
				future.complete(MessageResult.NOEXIST);
				return future;
			}
			switch (messageIndex.getMessageType()) {
				case TEXT:
					future = sendOfflineText(message, messageIndex);
					break;
				case INVITE:
					future = invite(message, messageIndex);
					break;
				default:
					LOGGER.warn("unknown GroupOfflineMessage type return  INVALID");
					future.complete(MessageResult.INVALID);
			}


		} catch (Exception ex) {
			LOGGER.error(String.format("send error. messageId: %s", messageId), ex);
			future.complete(MessageResult.FAILURE);
		}

		return future;
	}

	/**
	 * 走T端SessionMode 的逻辑. 只是单纯的利用原来的dialog ,
	 * 或者按照原来的方式激活一个dialog.激活后有dialog 自己检查这个人是否存在离线.
	 *
	 * @param message
	 * @param messageIndex
	 * @return
	 */
	public Future<MessageResult> sendOfflineText(MessageBase message, GroupOfflineMessageIndex messageIndex) {
		Future<MessageResult> future = new Future<>();
		GroupIndex groupIndex = null;
		GroupInfo groupInfo = null;
		try {
			groupIndex = groupService.getGroupIndex(messageIndex.getGroupId());
			if (null == groupIndex) {
				future.complete(MessageResult.INVALID);
				LOGGER.warn(String.format("getGroupIndex is null messageIndex=%s ,messageBase=%s", messageIndex, message));
				return future;
			}
			groupInfo = groupService.getGroupInfo(groupIndex);
			if (null == groupInfo) {
				future.complete(MessageResult.INVALID);
				LOGGER.warn(String.format("getGroupInfo is null messageIndex=%s ,messageBase=%s", messageIndex, message));
				return future;
			}
			//TODO 这地方万一不是个TelURI 呢...
			GroupMessageArgs groupMessageArgs = new GroupMessageArgs();
			groupMessageArgs.setGroupId(groupInfo.getGroupId());
			groupMessageArgs.setToMobile(messageIndex.getReceiver());
			groupMessageArgs.setDomain(GroupConfiguration.INSTANCE.getGroupDomain());
			groupMessageArgs.setConversationId(groupInfo.getConversationId());
			groupMessageArgs.setIsOnlyActiveOfflineMsg(true);
			groupMessageArgs.setSubject(groupInfo.getSubject());
			terminalService.sendTextMessage(groupMessageArgs);
			future.complete(MessageResult.SUCCESS);
			return future;

		} catch (Exception e) {
			LOGGER.error(String.format("invite offline send error  messageIndex=%s,messageBase=%s", messageIndex, message), e);
			future.complete(MessageResult.FAILURE);
			return future;
		}

	}

	/**
	 * 加入群邀请. 再次激活T端逻辑.
	 *
	 * @param message
	 * @param messageIndex
	 * @return
	 */
	public Future<MessageResult> invite(MessageBase message, GroupOfflineMessageIndex messageIndex) {

		Future<MessageResult> future = new Future<>();
		GroupIndex groupIndex = null;
		GroupInfo groupInfo = null;
		try {
			groupIndex = groupService.getGroupIndex(messageIndex.getGroupId());
			if (null == groupIndex) {
				future.complete(MessageResult.INVALID);
				LOGGER.warn(String.format("getGroupIndex is null messageIndex=%s ,messageBase=%s", messageIndex, message));
				return future;
			}
			groupInfo = groupService.getGroupInfo(groupIndex);
			if (null == groupInfo) {
				future.complete(MessageResult.INVALID);
				LOGGER.warn(String.format("getGroupInfo is null messageIndex=%s ,messageBase=%s", messageIndex, message));
				return future;
			}
			//TODO 这地方万一不是个TelURI 呢...
			MobileNo referBy = MobileNo.parseFrom(message.getMessageReferBy());
			GroupInviteArgs entity = new GroupInviteArgs();
			entity.setSubject(groupInfo.getSubject());
			entity.setGroupId(groupInfo.getGroupId());
			entity.setConversationId(groupInfo.getConversationId());
			entity.setDomain(GroupConfiguration.INSTANCE.getGroupDomain());
			entity.setReferredBy(referBy);
			entity.setReferredTo(messageIndex.getReceiver());
			entity.setOffline(true);
			// 先删除了吧, 如果邀请失败需要离线的话由 T端逻辑继续离线.
			offlineMessageService.deliveredInvite(messageIndex);
			terminalService.inviteJoinGroup(entity);
			future.complete(MessageResult.SUCCESS);
			return future;

		} catch (Exception e) {
			LOGGER.error(String.format("invite offline send error  messageIndex=%s ,messageBase=%s", messageIndex, message), e);
			future.complete(MessageResult.FAILURE);
			return future;
		}

	}


}

